package com.hmall.item.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.pojo.RequestParams;
import com.hmall.item.service.IItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {
    @Autowired
    ItemMapper itemMapper;

    @Override
    public PageDTO<Item> search(RequestParams params) {
        Date before = null;
        Date after = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        int page = params.getPage();
        int size = params.getSize();
        LambdaQueryWrapper<Item> wrapper = new LambdaQueryWrapper<>();
        if (params.getName() != null && !params.getName().equals("")) {
            wrapper.eq(Item::getName, params.getName());
        }
        if (params.getBrand() != null && !params.getBrand().equals("")) {
            wrapper.eq(Item::getName, params.getBrand());
        }
        if (params.getCategory() != null && !params.getCategory().equals("")) {
            wrapper.eq(Item::getName, params.getCategory());
        }
        if (params.getDateRange().length != 0) {
            try {
                before = dateFormat.parse(params.getDateRange()[0]);
                after = dateFormat.parse(params.getDateRange()[1]);
                wrapper.between(Item::getCreateTime, before, after);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        Page<Item> page1 = new Page<>(page, size);
        Page<Item> page2 = page(page1, wrapper);
        List<Item> list = page2.getRecords();
        long total = page2.getTotal();
        PageDTO<Item> pageDTO = new PageDTO<>();
        pageDTO.setList(list);
        pageDTO.setTotal(total);
        return pageDTO;
    }
}
